package castledefense.game.render.effects;

import castledefense.data.GameData;
import castledefense.data.Resources;
import castledefense.logic.Map;

import com.badlogic.gdx.graphics.g2d.ParticleEffect;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class UnitDeath {

	private final static int MAX = 16;

	private ParticleEffect blast;
	private final Effect[] pool = new Effect[MAX];
	private boolean[] doable = new boolean[MAX];
	private int current = 0;

	public UnitDeath(int type) {
		if (type == GameData.fire)
			blast = Resources.fireUnitDeath;
		else if (type == GameData.water)
			blast = Resources.waterUnitDeath;
		else if (type == GameData.earth)
			blast = Resources.earthUnitDeath;
		else if (type == GameData.air)
			blast = Resources.airUnitDeath;
		else
			System.out.println("Cant load particle effect type" + type);

		for (int i = 0; i < MAX; i++)
			pool[i] = new Effect(blast);
	}

	public void dispose() {
		for (int i = 0; i < MAX; i++) {
			pool[i].dispose();
		}
	}

	public void render(SpriteBatch spriteBatch, float delta) {

		for (int i = 0; i < MAX; i++) {
			if (doable[i]) {
				pool[i].render(spriteBatch, delta);
			}
		}
	}

	public void update(int delta) {

		for (int i = 0; i < MAX; i++) {
			if (doable[i]) {
				doable[i] = pool[i].update();
			}
		}
	}

	public void addBlast(float x, float y) {
		pool[current].set(x*Map.cellWidth, y*Map.cellWidth);
		doable[current] = true;
		current++;
		if (current >= MAX) {
			current = 0;
		}
	}

	private class Effect {
		private ParticleEffect blast;

		public Effect(ParticleEffect blast) {
			this.blast = new ParticleEffect(blast);
		}

		public void dispose() {
			blast.dispose();
		}

		public void render(SpriteBatch spriteBatch, float delta) {
			blast.draw(spriteBatch, delta);
		}

		/**
		 * update method. Report true if effect is finished and can be freed to
		 * pool
		 */
		public boolean update() {
			return !blast.isComplete();
		}

		public void set(float x, float y) {
			blast.setPosition(x, y);
			blast.start();
		}
	}

}
